package cn.superchart.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.superchart.common.base.BaseUserDetails;
import cn.superchart.common.properties.SecurityProperties;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;

public class ScUserContext {

    private static final SecurityProperties securityProperties = SpringUtil.getBean(SecurityProperties.class);

    // 默认情况下 白名单 接口不需要获取userId
    public static String getUserId(){
        if(!checkUrlIgnore()){
            BaseUserDetails userDetails = userDetails();
            if (Checker.BeNotNull(userDetails)) {
                return userDetails.getUserId();
            }
        }
        return null;
    }


    public static BaseUserDetails getUser(){
        if(!checkUrlIgnore()){
            BaseUserDetails userDetails = userDetails();
            if (Checker.BeNotNull(userDetails)) {
                return userDetails;
            }
        }
        return null;
    }

    // 默认情况下 白名单 接口不需要获取userId 如过强制的话 也会获取
    public static String getUserId(boolean force){
        if(!checkUrlIgnore() || force){
            BaseUserDetails userDetails = userDetails();
            if (Checker.BeNotNull(userDetails)) {
                return userDetails.getUserId();
            }
        }
        return null;
    }

    public static String getAccount(){
        if(!checkUrlIgnore()){
            BaseUserDetails userDetails = userDetails();
            if (Checker.BeNotNull(userDetails)) {
                return userDetails.getUsername();
            }
        }
        return null;
    }

    public static Boolean checkUrlIgnore(){
        String url = RequestContextUtil.getCurrentRequest().getRequestURI();
        String[] whiteList =  securityProperties.getWhiteList();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        if(Checker.BeNotEmpty(whiteList)){
            for(String whiteUrl : whiteList){
                boolean ignore = pathMatcher.match(whiteUrl,url);
                if(ignore){
                    return true;
                }
            }
        }
        return false;
    }


    public static BaseUserDetails userDetails(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            BaseUserDetails baseUserDetails = (BaseUserDetails)authentication.getPrincipal();
            return baseUserDetails;
        }
        return null;
    }
}
